<?php
class Backoffice_FlagController extends CC_Controller
{
    /**
     * List all flags with pagination
     * 
     * URL: /backoffice/flag/index
     */
    public function indexAction()
    {
        // DQL query to be paginated and passed to view
        $dql = $this->_em->createQuery('SELECT f FROM CC\Entity\Flag f ORDER BY f.name ASC');
        
        $flags = new Zend_Paginator(new DoctrineExtensions\Paginate\PaginationAdapter($dql));
        $flags->setCurrentPageNumber($this->_getPage())
              ->setItemCountPerPage(20)
              ->setPageRange(10);
        
        $this->view->flags = $flags;
    }
    
    /**
     * Create a new flag
     * 
     * URL: /backoffice/flag/create
     */
    public function createAction()
    {
        // Create form
        $form = new Backoffice_Model_FormFlag();
        $form->setAction('/backoffice/flag/create');
        
        // Check if form was posted
        if($this->getRequest()->isPost())
        {
            // Check if form was valid
            if($form->isValid($this->_request->getPost()))
            {
                // Process form
                $flag = new CC\Entity\Flag();
                $flag->setName($form->getValue('name'));
                $flag->setDescription($form->getValue('description'));
                $flag->setActiveOnDev(in_array('dev', $form->getValue('zones')));
                $flag->setActiveOnProduction(in_array('prod', $form->getValue('zones')));
                
                $this->_em->persist($flag);
                $this->_em->flush();
                
                // Display message and redirect back to index
                $this->_helper->messenger('success', sprintf(Zend_Registry::get('config')->messages->flag->create, $form->getValue('name')));
                return $this->_helper->redirector('index', 'flag', 'backoffice');
            }
            else
            {
                // Assign errors to view
                $this->view->errors = $form->getErrors();
            }
        }
        
        // Display form
        $this->view->form = $form;
    }
    
    /**
     * Update the flag passed via the 'id' GET param
     * 
     * URL: /backoffice/flag/update/id/?
     */
    public function updateAction()
    {
        // Create form and set update specific properties
        $request = $this->getRequest();
        $form = new Backoffice_Model_FormFlag();
        $form->getElement('submit')->setLabel('Update Flag');
        /** @var CC\Entity\Flag */
        $flag = $this->_em->getRepository('CC\Entity\Flag')->findOneById($this->_getParam('id'));
        
        // Check if flag is valid
        if($flag === null)
        {
            // Display message on redirect
            $this->_helper->messenger('error', 'Invalid privilege');
            return $this->_helper->redirector('index', 'privilege', 'backoffice');
        }
        else 
        {
            // Check if request is POST
            if($request->isPost())
            {
                // Check if form is valid
                if($form->isValid($this->_request->getPost()))
                {
                    // Process update form
                    $flagName = $flag->getName();
                    $flag->setName($form->getValue('name'));
                    $flag->setDescription($form->getValue('description'));
                    $flag->setActiveOnDev(in_array('dev', $form->getValue('zones')));
                    $flag->setActiveOnProduction(in_array('prod', $form->getValue('zones')));
                    
                    $this->_em->persist($flag);
                    $this->_em->flush();
                    
                    // Display message on redirect
                    $this->_helper->messenger('success', sprintf(Zend_Registry::get('config')->messages->flag->update, $flagName));
                    return $this->_helper->redirector('index', 'flag', 'backoffice');
                }
                else
                {
                    // Assign errors to view
                    $this->view->errors = $form->getErrors();
                }
            }
            else 
            {
                // Populate zones array
                $zones = array();
                ($flag->isActiveOnDev() == '1' ? $zones[] = 'dev' : null);
                ($flag->isActiveOnProduction() == '1' ? $zones[] = 'prod' : null);
                
                // Populate form
                $formData = array(
                    "name" => $flag->getName(),
                    "description" => $flag->getDescription(),
                    "zones" => $zones
                );
                
                $form->populate($formData);
            }
        }
        
        // Display form
        $this->view->form = $form;
    }
    
    /**
     * Delete the flag passed by the 'id' GET param
     * 
     * URL: /backoffice/flag/delete/id/?
     */
    public function deleteAction()
    {
        $request = $this->getRequest();
        
        // Ensure an ID is set, otherwise redirect to index with error message
        if(!isset($request->id))
        {
            $this->_helper->messenger('error', Zend_Registry::get('config')->messages->flag->invalid);
            return $this->_helper->redirector('index', 'flag', 'backoffice');
        }
            
        // Get flag entity
        $flag = $this->_em->getRepository('CC\Entity\Flag')->findOneById($request->id);
        
        // Check if flag is valid
        if($flag !== null)
        {
            // Remove flag
            $flagName = $flag->getName();
            
            $this->_em->remove($flag);
            $this->_em->flush();
            
            // Display message on redirect
            $this->_helper->messenger('success', sprintf(Zend_Registry::get('config')->messages->flag->delete, $flagName));
            return $this->_helper->redirector('index', 'flag', 'backoffice');
        }
        else
        {
            // If it got here, the flag ID was invalid, redirect with error message
            $this->_helper->messenger('error', Zend_Registry::get('config')->messages->flag->invalid);
            return $this->_helper->redirector('index', 'flag', 'backoffice');
        }
    }
    
    /**
     * Toggle which zone the flag is enabled on.
     * By passing the 'id' and 'zone' GET param, this 
     * method will enable the flag on the zone if the 
     * flag is disabled, and vica-versa
     * 
     * URL: /backoffice/flag/toggle/zone/?/id/?
     */
    public function toggleAction()
    {
        $request = $this->getRequest();
        
        // Ensure there are parameters
        if($request->getParam('zone') === null || $request->getParam('id') === null)
        {
            $this->_helper->messenger('error', Zend_Registry::get('config')->messages->flag->invalid);
            return $this->_helper->redirector('index', 'flag', 'backoffice');
        }
        
        /** @var CC\Entity\Flag */
        $flag = $this->_em->getRepository('CC\Entity\Flag')->findOneById($request->getParam('id'));
        
        // Check if flag is valid
        if($flag !== null)
        {
            $flagName = $flag->getName();
            
            // Toggle the flag zone
            switch($request->getParam('zone'))
            {
                case 'dev':
                    $zone = 'development';
                    $currentState = $flag->isActiveOnDev();
                    $flag->setActiveOnDev(!$currentState);
                    break;
                case 'prod':
                    $zone = 'production';
                    $currentState = $flag->isActiveOnProduction();
                    $flag->setActiveOnProduction(!$currentState);
                    break;
                default:
                    
                    break;
            }
            
            $this->_em->persist($flag);
            $this->_em->flush();
             
            // Display message and redirect
            $this->_helper->messenger('success', sprintf(Zend_Registry::get('config')->messages->flag->toggle, $flagName, (!$currentState ? 'enabled' : 'disabled'), $zone));
            return $this->_helper->redirector('index', 'flag', 'backoffice');
        }
        else
        {
            // Invalid flag, display message and redirect to index action
            $this->_helper->messenger('error', Zend_Registry::get('config')->messages->flag->invalid);
            return $this->_helper->redirector('index', 'flag', 'backoffice');
        }
    }
}